package com.phpxiu.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.phpxiu.app.adapter.FriendPickerAdapter;
import com.phpxiu.app.adapter.holder.FriendPickerViewHolder;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.list.WatchFriend;
import com.phpxiu.app.model.response.FriendPickerModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 吴金洲 on 2016/8/4
 */
public class FriendsPicker extends UIBase implements View.OnClickListener,PullToRefreshView.OnRefreshListener2<ListView>,AdapterView.OnItemClickListener  {
    public final static String TAG="FriendsPicker";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private List<String>ids=new ArrayList<String>();//已选择
    private List<WatchFriend>friends=new ArrayList<WatchFriend>();
    private PullToRefreshListView ptrRefreshView;
    private ListView mListView;
    private LinearLayout headView;
    private FriendPickerAdapter mAdapter;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private Button finishBtn;
    private String submitLabel,cancelLabel;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friends_picker);
        init();
    }

    /**
     * 初始化界面
     */
    private void init(){
        finishBtn=(Button)findViewById(R.id.finish_btn);
        submitLabel=getString(R.string.list_menus_submit);
        cancelLabel=getString(R.string.list_menus_cancel);
        finishBtn.setOnClickListener(this);
        ptrRefreshView=(PullToRefreshListView)findViewById(R.id.friends_pull_refresh_list);
        mListView=ptrRefreshView.getRefreshableView();
        AbsListView.LayoutParams params=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headView=(LinearLayout)LayoutInflater.from(this).inflate(R.layout.friend_picker_list_head_view,null);
        headView.setLayoutParams(params);
        mListView.addHeaderView(headView);
        //emptyView.setMsg("您还没有相互关注的好友");
        mListView.setOnItemClickListener(this);
        mListView.setDivider(null);
        mAdapter=new FriendPickerAdapter(this,friends);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    /**
     * 初始化请求
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder(false);
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            pageIndex=pageIndex==1?2:pageIndex;
            param.put("pageIndex",pageIndex);
        }
        OKHttp.post(HttpConfig.API_GET_SPECIAL_FRIENDS, param.jsonParam(), TAG, new OKHttpUIHandler(FriendPickerModel.class) {
            @Override
            public void onSuccess(Object model) {
                FriendPickerModel m = (FriendPickerModel) model;
                KKYUtil.log(TAG, "互粉列表数据：" + m.getResponseStr());
                try {
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        friends.clear();
                        pageIndex = 1;
                    }

                    friends.addAll(m.getData().getUserlist());
                    if(mOpera == HttpConfig.REQUEST_OPERA_LOAD){
                        if (currentAllRecords > 0 && friends.size() > 0 && friends.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    mAdapter.refresh();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                listEmpty(friends.size() == 0);
            }

            @Override
            public void onErr(String errMsg) {
                listEmpty(friends.size() == 0);
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.finish_btn:
                onFinish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof FriendPickerViewHolder){
            WatchFriend friend=((FriendPickerViewHolder)view.getTag()).getFriend();
            if(friend.isSelected()){
                ids.remove(friend.getUid());
                friend.setSelected(false);
            }else{
                ids.add(friend.getUid());
                friend.setSelected(true);
            }
            mAdapter.notifyDataSetChanged();
            if(ids.size()>0){
                finishBtn.setText(submitLabel+"("+ids.size()+")");
            }else{
                finishBtn.setText(cancelLabel);
            }
            for (String item:ids){
                KKYUtil.log("当前选中id:"+item);
            }
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(friends.size()!=0&&friends.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptrRefreshView != null) {
            if(isEmpty) {
                ptrRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptrRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }

    /**
     * 结束操作
     */
    private void onFinish(){
        if(ids.size()>0){
            Intent intent=new Intent();
            intent.putExtra(PublishLive.EXTRA_FRIEND_IDS, ids.toArray(new String[1]));
            setResult(RESULT_OK,intent);
        }else{
            setResult(RESULT_CANCELED);
        }
        for (String item:ids){
            KKYUtil.log("当前选中id:"+item);
        }
        finish();
    }
}
